<template>
	<view>
		<!-- 固定顶栏，包含天气和导航 -->
		<view class="fixed-header">
			<!-- 天气信息 -->
			<view class="weather-info">
				<text class="weather-item">{{time}}</text>
				<text class="weather-item">{{week}}</text>
				<text class="weather-item">{{city}}</text>
				<text class="weather-item">{{high}}</text>
				<text class="weather-item">{{low}}</text>
				<text class="weather-item">{{Wtype}}</text>
			</view>

			<!-- 可左右滑动的导航栏 -->
			<scroll-view class="nav-scroll" scroll-x="true" :scroll-left="scrollLeft" scroll-with-animation>
				<view class="nav-container">
					<view v-for="(item, index) in navList" :key="index" class="nav-item"
						:class="{active: activeNav === index}" @tap="switchNav(index)">
						<text>{{item}}</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 新闻列表区域 - 使用普通view -->
		<view class="news-container">
			<!-- 下拉刷新提示 -->
			<view v-if="showUpdateTip" class="update-tip">
				<text>为您更新了{{refreshCount}}条内容</text>
			</view>

			<!-- 新闻列表 -->
			<view v-for="item in NewsList" :key="item.title" class="news-item">
				<TopTextNews :title="item.title" :isTop="item.isTop" :author="item.author" :comment="item.comment"
					:isAd="item.isAd" :timedata="item.timedate" :images="item.images || []"></TopTextNews>
			</view>
		</view>
	</view>
</template>

<script>
	import newsdata from '../../../data/news.json';
	import TopTextNews from '../../../components/TopTextNews.vue';
	export default {
		components: {
			TopTextNews
		},
		data() {
			return {
				NewsList: [],
				originalNewsList: [], // 保存原始数据

				// 天气数据
				time: "",
				city: "",
				high: "",
				low: "",
				week: "",
				Wtype: "",

				// 导航数据
				navList: ['要闻', '推荐', '关注流', '24小时', '娱乐', '泉州', '财经'],
				activeNav: 0,
				scrollLeft: 0,

				// 下拉刷新
				showUpdateTip: false,
				refreshCount: 0,

				// 定时器
				weatherTimer: null
			}
		},
		methods: {
			// 获取天气数据
			getWeather() {
				uni.request({
					url: 'http://t.weather.sojson.com/api/weather/city/101230501',
					success: (res) => {
						console.log("天气获取成功:" + res.data.time);
						this.time = res.data.data.forecast[0].ymd;
						this.week = res.data.data.forecast[0].week;
						this.city = res.data.cityInfo.city;
						this.high = res.data.data.forecast[0].high;
						this.low = res.data.data.forecast[0].low;
						this.Wtype = res.data.data.forecast[0].type;
					},
					fail: (eMsg) => {
						console.log("天气获取失败:" + eMsg);
						// 如果API调用失败，使用默认值
						this.time = "2025-12-05";
						this.week = "星期五";
						this.city = "泉州市";
						this.high = "高温 19℃";
						this.low = "低温 12℃";
						this.Wtype = "晴";
					}
				});
			},

			// 设置定时获取天气
			setupWeatherTimer() {
				// 先清除已有定时器
				if (this.weatherTimer) {
					clearInterval(this.weatherTimer);
				}

				// 每2小时获取一次天气
				this.weatherTimer = setInterval(() => {
					console.log("定时获取天气数据...");
					this.getWeather();
				}, 2 * 60 * 60 * 1000); // 2小时
			},

			// 加载新闻数据
			// 改造后的 loadNewsData 方法
			async loadNewsData() {
			  try {
			    const db = uniCloud.database();
			    const result = await db.collection('news_list')
			      .field('title,author,comment,timedate,isTop,isAd,images,create_time') // 指定返回的字段
			      .orderBy('create_time', 'desc')
			      .get();
			
			    console.log('从云数据库获取新闻列表成功，数据条数:', result.result.data.length);
			
			    if (result.result.data.length > 0) {
			      this.NewsList = result.result.data;
			      this.originalNewsList = [...result.result.data];
			      this.refreshCount = this.NewsList.length;
			    } else {
			      this.NewsList = [];
			      console.warn('云端新闻列表为空');
			    }
			  } catch (error) {
			    console.error('获取新闻数据失败，详细错误:', error);
			    uni.showToast({
			      title: `获取新闻失败: ${error.message || '未知错误'}`,
			      icon: 'none',
			      duration: 3000
			    });
			  }
			},

			// 切换导航
			switchNav(index) {
				this.activeNav = index;

				// 点击导航后随机排序新闻
				this.randomSortNews();
			},

			// 随机排序新闻
			randomSortNews() {
				const shuffled = [...this.NewsList];
				for (let i = shuffled.length - 1; i > 0; i--) {
					const j = Math.floor(Math.random() * (i + 1));
					[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
				}
				this.NewsList = shuffled;
			},

			// 下拉刷新
			onRefresh() {
				// 随机排序新闻
				this.randomSortNews();

				// 更新刷新数量
				this.refreshCount = this.NewsList.length;

				// 显示更新提示
				this.showUpdateTip = true;

				// 3秒后隐藏更新提示
				setTimeout(() => {
					this.showUpdateTip = false;
				}, 3000);
			}
		},
		onLoad() {
			// 初始获取天气
			this.getWeather();

			// 设置定时获取天气
			this.setupWeatherTimer();

			// 加载新闻数据
			this.loadNewsData();
		},
		onPullDownRefresh() {
			// 调用下拉刷新方法
			this.onRefresh();

			// 停止下拉刷新动画
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onUnload() {
			// 页面卸载时清除定时器
			if (this.weatherTimer) {
				clearInterval(this.weatherTimer);
				this.weatherTimer = null;
			}
		}
	}
</script>

<style>
	/* 页面基础样式 */
	page {
		height: 100%;
		overflow-y: auto;
		/* 确保页面可以滚动 */
	}

	/* 固定顶栏 */
	.fixed-header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1000;
		background-color: #ffffff;
		border-bottom: 1px solid #f0f0f0;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	/* 天气信息 */
	.weather-info {
		display: flex;
		flex-wrap: nowrap;
		padding: 10rpx 20rpx;
		background-color: #f9f9f9;
		overflow-x: auto;
		white-space: nowrap;
		height: 50rpx;
		line-height: 50rpx;
	}

	.weather-item {
		font-size: 24rpx;
		color: #666;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	/* 导航栏滚动区域 */
	.nav-scroll {
		width: 100%;
		height: 80rpx;
		white-space: nowrap;
		background-color: #ffffff;
	}

	.nav-container {
		display: inline-flex;
		height: 100%;
		padding: 0 20rpx;
	}

	.nav-item {
		display: inline-flex;
		align-items: center;
		height: 100%;
		padding: 0 30rpx;
		font-size: 32rpx;
		color: #666;
		flex-shrink: 0;
		position: relative;
	}

	.nav-item.active {
		color: #f00;
		font-weight: bold;
	}

	.nav-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 20rpx;
		right: 20rpx;
		height: 4rpx;
		background-color: #f00;
		border-radius: 2rpx;
	}

	/* 新闻容器 - 使用普通view，不设置固定高度 */
	.news-container {
		width: 100%;
		margin-top: 80rpx;
		/* 固定顶栏的高度：天气50rpx + 导航80rpx = 130rpx */
		padding-bottom: 20rpx;
		/* 底部留点空间 */
		box-sizing: border-box;
	}

	.news-item {
		margin: 20rpx;
	}

	/* 更新提示 */
	.update-tip {
		background-color: #f0f8ff;
		padding: 20rpx;
		text-align: center;
		font-size: 28rpx;
		color: #007AFF;
		border-bottom: 1px solid #e0e0e0;
		animation: fadeInOut 3s ease-in-out;
	}

	@keyframes fadeInOut {

		0%,
		100% {
			opacity: 0;
		}

		10%,
		90% {
			opacity: 1;
		}
	}
</style>